package com.inews.base.security.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.inews.base.security.Constants;
import com.inews.base.security.repository.SecurityDao;
import com.inews.base.security.vo.SecOrgVo;
import com.inews.business.entity.TblBaseOrg;

@Service
public class SecOrgServiceImpl implements SecOrgService {

	@Autowired
	private SecurityDao securityDao;

	/**
	 * 查询机构(包括该机构下的子机构).
	 * 
	 * @param orgId
	 *            the org id
	 * @return the list
	 */
	public List<String> findSubOrgList(String orgId) {
		List<String> orgIdList = new ArrayList<String>();
		List<TblBaseOrg> orgPoList = new ArrayList<TblBaseOrg>();
		try {
			// 查询出所有的机构
			orgPoList = securityDao.findTblBaseOrgPo();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, SecOrgVo> secOrgVoMap = new HashMap<String, SecOrgVo>();
		for (TblBaseOrg orgPo : orgPoList) {
			SecOrgVo secOrgVo = new SecOrgVo();
			secOrgVo.setOrgId(orgPo.getOrgId());
			secOrgVo.setSuperOrgId(orgPo.getSupOrgId());
			secOrgVoMap.put(orgPo.getOrgId(), secOrgVo);
		}
		assembleChildOrg(secOrgVoMap);
		travelOrgTree(secOrgVoMap, orgId, orgIdList);
		return orgIdList;
	}

	
	/**
	 * 装配每一个机构的子机构.
	 * 
	 * @param orgMap
	 *            the org map
	 */
	private void assembleChildOrg(Map<String, SecOrgVo> secOrgVoMap) {
		if (secOrgVoMap.get(Constants.ORG_ROOT) == null) {
			SecOrgVo temproot = new SecOrgVo();
			temproot.setOrgId(Constants.ORG_ROOT);
			temproot.setSuperOrgId(Constants.ORG_ROOT);
			secOrgVoMap.put(Constants.ORG_ROOT, temproot);
		}
		for (Map.Entry<String, SecOrgVo> entry : secOrgVoMap.entrySet()) {
			SecOrgVo tempResource = entry.getValue();
			if (!tempResource.getOrgId().equals(Constants.ORG_ROOT)) {
				// 根据上级机构ID得到上级机构
				String supOrgId = tempResource.getSuperOrgId();
				SecOrgVo supOrgVo = secOrgVoMap.get(supOrgId);
				if (supOrgVo != null) {
					// 上级机构加入该子机构
					supOrgVo.getChildrenOrg().add(tempResource);
				}
			}

		}
	}

	
	/**
	 * 得到用户所在机构的所有子机构.
	 *
	 * @param orgmap the orgmap
	 * @param Orgid the orgid
	 * @param orglist the orglist
	 */
	private void travelOrgTree(Map<String, SecOrgVo> secOrgVoMap, String orgId, List<String> orgList) {
		SecOrgVo vo = secOrgVoMap.get(orgId);
		if (vo != null) {
			orgList.add(orgId);
			List<SecOrgVo> children = vo.getChildrenOrg();
			for (SecOrgVo m : children) {
				String childOrgId = m.getOrgId();
				travelOrgTree(secOrgVoMap, childOrgId, orgList);
			}
		}
	}

}
